const jwt = require('jsonwebtoken')
const {JWT_SECRET} = require('../config/config.default')
const {TokenExpiredError, invalidToken} = require('../consitant/error')
const auth = async (ctx, next) => {
    let {token = '', authorization = ''} = ctx.request.header
   // token = token.replace('Bearer ', '')
    //postman验证
     const postman = authorization.replace('Bearer ', '')
    token=postman===""?token:postman
    try {
        const user = jwt.verify(token, JWT_SECRET)
        //user就是用户信息，挂载在上面
        ctx.state.user = user
        await next()
    } catch (err) {
        switch (err.name) {
            case 'TokenExpiredError':
                console.error("tocken已过期")
                return ctx.app.emit('error', TokenExpiredError, ctx)
            case "JsonWebTokenError":
                console.error("无效的token")
                return ctx.app.emit('error', invalidToken, ctx)
        }
    }


}

module.exports = {
    auth
}